//
//  CZOAuthViewController.swift
//  weibo
//
//  Created by Apple on 16/3/10.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import SVProgressHUD

let Appkey = "3914795679"//"2427214851"
let AppSecret = "36a1ecc7c2cee5df5c0e1c3928df6b5e"//"46b33ff3b870f820add120032ce44386"
let Redirect_uri = "http://www.baidu.com"

class CZOAuthViewController: UIViewController,UIWebViewDelegate {

    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        //  设置代理
        webView.delegate = self
        //  设置view 为 webView
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "微博登录"
        setNavigationItem()
        //
        requestOAuth()
    }
    
    private func setNavigationItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
    }
    //  取消登录事件
    @objc private func cancelAction() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    //  自动填充事件
    @objc private func autoFillAction() {
        
        //  执行javascript
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value='18911412662';document.getElementById('passwd').value='19880828';")
        
    }
    
    //  请求第三方登录
    private func requestOAuth() {
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(Appkey)&redirect_uri=\(Redirect_uri)"
        
        let url = NSURL(string: urlStr)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }
    
    
    
   

}
//  UIWebViewDelegate 代理
extension CZOAuthViewController {
    
    // MARK:    UIWebView代理
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        guard let url = request.URL?.absoluteString else {
            return false
        }
        
        //  不是我们想要的开头地址就放行
        if !url.hasPrefix(Redirect_uri) {
            return true
        }
        
        
        
        //  代码到这个地方去code，是我们关心的地址
        let query = request.URL!.query!
        //  判断如果是不是以code=,如果是则进行获取accesstoken
        if query.hasPrefix("code=") {
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
            
            //  获取accesstoken
            CZUserAccountViewModel.sharedAccount.requestAccesstoken(code, complete: { (isSuccess) -> () in
                //  登录成功
                if isSuccess {
                
                    //  dismis当前控制器，进入首页
                    print("登录成功")
                    //  隐藏旋转
                    SVProgressHUD.dismiss()
                    
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //  appdelegate监听通知
                        NSNotificationCenter.defaultCenter().postNotificationName(CZSwitchRootVCNotifation, object: self)
                    })
                    
                   
                    
                } else {
                    //  登录失败
                    SVProgressHUD.showErrorWithStatus("登录失败")
                }
                
            })
            
        } else {
            //  点击取消则dismiss掉
            cancelAction()
        }
        
        
        //  返回false说明请求失败了
        return false
        
        
    }
    
    //  开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //  加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}
